package logic

import (
	"context"
	"product/model/mysql"

	"product/goodsrpc/goodsrpc"
	"product/goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListGoodsLogic {
	return &ListGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListGoodsLogic) ListGoods(in *goodsrpc.ListGoodsRequest) (*goodsrpc.ListGoodsResponse, error) {
	// todo: add your logic here and delete this line

	size := in.Size
	page := in.Page
	if page <= 0 {
		page = 1
	}
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	offset := (page - 1) * size

	var findgoods []mysql.Good
	mysql.DB.Where("user_id=?", in.Userid).Order("price desc").Offset(int(offset)).Limit(int(size)).Find(&findgoods)

	var goods []*goodsrpc.GoodsList
	for _, i2 := range findgoods {
		list := goodsrpc.GoodsList{
			Name:   i2.Name,
			Img:    i2.Img,
			UserId: int64(i2.UserId),
			Num:    int64(i2.Num),
			Price:  int64(i2.Price),
		}
		goods = append(goods, &list)
	}

	return &goodsrpc.ListGoodsResponse{List: goods}, nil
}
